package com.gisuni.sddc.service;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.json.JSONArray;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;

import com.gisuni.sddc.dao.UserOrganizationDao;
import com.gisuni.sddc.model.Organization;
import com.gisuni.sddc.model.Response;
import com.gisuni.sddc.model.UserOrganization;
import com.gisuni.sddc.util.StringUtil;

@IocBean
public class UserOrganizationService {

	private Log log = Logs.getLog(UserOrganizationService.class);
	@Inject
	private UserOrganizationDao  userOrganizationDao;

	


	/**
	 * 查询数据
	 * 
	 * @param 
	 * @return
	 */
	public Response queryBaseUserAll(int from,int to,String name,String userId) {
		Response response = new Response();
		response.setSuccess(false);
		String Result=null;
		StringBuffer selectstr=null;
		String andSelect = "";
		try {
			/*
			  select r1.userid,r1.username,r1.displayname ,r2.organization_name organizationCompanyName ,r3.organization_name organizationBusinessName ,r4.id organizationDevelopId，r4.organization_name organizationDevelopName,r5.quota from ( 
			  select t.userid,t.username,t.displayname,t1.organization_company_id,t1.organization_business_id,t1.organization_develop_id from userinfo t left join user_organization t1 on t.userid = t1.user_id) r1 
			  left join  organization r2 on r1.organization_company_id=r2.id 
			  left join  organization r3 on r1.organization_business_id = r3.id 
			  left join  organization r4 on r1.organization_develop_id=r4.id 
			  left join  organization_user_quota r5 on r1.organization_develop_id=r5.organization_develop_id
			 * */
			selectstr = new StringBuffer();
 
			selectstr.append("select r1.userid,r1.username,r1.displayname ,r2.organization_name organizationCompanyName ,r3.organization_name organizationBusinessName ,r4.id organizationDevelopId,r4.organization_name organizationDevelopName,r5.quota from ( ");
			selectstr.append("select t.userid,t.username,t.displayname,t1.organization_company_id,t1.organization_business_id,t1.organization_develop_id from SDDCONEMAP.userinfo t left join SDDCGISPLATFORM.user_organization t1 on t.userid = t1.user_id) r1 ");
			selectstr.append(" left join  SDDCGISPLATFORM.organization r2 on r1.organization_company_id=r2.id ");
			selectstr.append(" left join  SDDCGISPLATFORM.organization r3 on r1.organization_business_id = r3.id ");
			selectstr.append(" left join  SDDCGISPLATFORM.organization r4 on r1.organization_develop_id=r4.id ");
			selectstr.append(" left join  SDDCGISPLATFORM.organization_user_quota r5 on r1.organization_develop_id=r5.organization_develop_id");
 
			selectstr.append(" where 1=1 ");
			if(!StringUtil.isNullOrEmpty(name)){
				andSelect=" and ( username like '%"+name.trim()+"%' or displayname like '%"+name.trim()+"%')";
		    }
			
			if(!StringUtil.isNullOrEmpty(userId)){
				andSelect=" and userid="+userId;
		    }
			
			
				Result= userOrganizationDao.queryBaseUserAll(from,to,selectstr+andSelect);
				
//				Map<String,Integer>  map = new HashMap<String,Integer>();
//				if(Result!=null && Result.length()>0){
//					for(int i=0;i<Result.length();i++){
//						JSONArray result=Result.
//					}
//			    	if(organizationDevelopId!=null){
//			    		if(map.get(organizationDevelopId)!=null){
//			    			
//			    		}else{
//			    			
//			    		}
//			    		
//			    	}
//				}
				String totalstr=" WHERE 1=1"+andSelect;
				response.setTotal(userOrganizationDao.queryBaseUsertotal(totalstr));

			if (Result==null) {
				return response;
			}
			response.setSuccess(true);
			response.setResult(Result);
			return response;
		} catch (Exception e) {
			log.error(e.getMessage());
			return response;
		}
	}
	

	public Response updateUserOrganization(UserOrganization userOrganization,String existFlag) {
		Response response = new Response();
		response.setSuccess(false);
		Boolean result = false;
		try {
			
			if(userOrganization!=null && String.valueOf(userOrganization.getUserId())!=null){
				Boolean flag = "".equals(userOrganization.getOrganizationCompanyId()) && "".equals(userOrganization.getOrganizationBusinessId()) && "".equals(userOrganization.getOrganizationDevelopId());
				//新增
				if("0".equals(existFlag)){
					if(flag){
						response.setSuccess(true);
						return response;
					}
//					 Boolean result = userOrganizationDao.addUserOrganization(userOrganization);
					 StringBuffer sbf = new StringBuffer("insert into SDDCGISPLATFORM.USER_ORGANIZATION(USER_ID,ORGANIZATION_COMPANY_ID,ORGANIZATION_BUSINESS_ID,ORGANIZATION_DEVELOP_ID)");
					 sbf.append(" values("+userOrganization.getUserId()+",'"+userOrganization.getOrganizationCompanyId()+"','"+userOrganization.getOrganizationBusinessId()+"','"+userOrganization.getOrganizationDevelopId()+"')");
					 result = userOrganizationDao.updateUserOrganization(sbf.toString());
 
				}else{
					//
					if(flag){
						StringBuffer sbf = new StringBuffer("delete from SDDCGISPLATFORM.USER_ORGANIZATION where USER_ID ="+userOrganization.getUserId());
						 result = userOrganizationDao.updateUserOrganization(sbf.toString());
					}else{
						
						StringBuffer sbf = new StringBuffer("update SDDCGISPLATFORM.USER_ORGANIZATION set USER_ID ="+userOrganization.getUserId());
						if(userOrganization.getOrganizationCompanyId()!=null){
							sbf.append(" ,ORGANIZATION_COMPANY_ID='"+userOrganization.getOrganizationCompanyId()+"'");
						}
						if(userOrganization.getOrganizationBusinessId()!=null){
							sbf.append(" ,ORGANIZATION_BUSINESS_ID='"+userOrganization.getOrganizationBusinessId()+"'");
						}
						if(userOrganization.getOrganizationDevelopId()!=null){
							sbf.append(" ,ORGANIZATION_DEVELOP_ID='"+userOrganization.getOrganizationDevelopId()+"'");
						}
						 sbf.append(" WHERE USER_ID="+userOrganization.getUserId());
						 
						 result = userOrganizationDao.updateUserOrganization(sbf.toString());
						 

					}
					 
				}

			}
			
			 if(result){
				 response.setSuccess(true);
			 }
 
		} catch (Exception e) {
			log.error(e.getMessage());
			return response;
		}
		return response;
	}


	public Response getOrganization(Organization organization) {
		Response response = new Response();
		response.setSuccess(false);
		String Result=null;
		StringBuffer selectstr=null;
 
		try {
			selectstr = new StringBuffer();
			selectstr.append("select id,organization_name,organization_type from SDDCGISPLATFORM.organization where 1=1 ");
			if( !StringUtil.isNullOrEmpty(organization.getParentId())){
				selectstr.append(" and parent_id='"+organization.getParentId()+"'");
		    }
			
			
				Result= userOrganizationDao.queryOrganization(selectstr.toString());

			if (Result==null) {
				return response;
			}
			response.setSuccess(true);
			response.setResult(Result);
			return response;
		} catch (Exception e) {
			log.error(e.getMessage());
			return response;
		}
	}


	public Response getOrganizationData(Organization organization) {
		Response response = new Response();
		response.setSuccess(false);
		String Result=null;
		StringBuffer selectstr=null;
 
		try {
			selectstr = new StringBuffer();
			  

			selectstr.append("select t.id,t.organization_name,t.organization_type,");
			selectstr.append("t1.organization_name PARENT_NAME,t2.displayname manager_user_name ,t.organization_manager_id, t.parent_id from sddcgisplatform.organization t ");
			selectstr.append("left join  sddcgisplatform.organization t1 on t.parent_id = t1.id ");
		    selectstr.append("left join  sddconemap.userinfo t2 on t.organization_manager_id = t2.userid where 1=1 "); 
		    
		    //组织名称、负责人名称模糊查询
			if( !StringUtil.isNullOrEmpty(organization.getOrganizationName())){
				selectstr.append(" and (t.organization_name like '%"+organization.getOrganizationName()+"%' ");
				selectstr.append(" or   t2.username like '%"+organization.getOrganizationName()+"%' ");
				selectstr.append(" or   t2.displayname like '%"+organization.getOrganizationName()+"%' )");
		    }		
			
			if( !StringUtil.isNullOrEmpty(organization.getOrganizationManagerId())){
				selectstr.append(" and organization_manager_id='"+organization.getOrganizationManagerId()+"'");
		    }
			
				Result= userOrganizationDao.queryOrganization(selectstr.toString());

			if (Result==null) {
				return response;
			}
			JSONArray resultJsonArr = new JSONArray(Result);
			response.setTotal(resultJsonArr.length());
			response.setSuccess(true);
			response.setResult(Result);
			return response;
		} catch (Exception e) {
			log.error(e.getMessage());
			return response;
		}

	}

	
	public Response addOrganization(Organization organization) {
		Response response = new Response();
		response.setSuccess(false);
		try {
			organization.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			Organization Result =  userOrganizationDao.addOrganization(organization);
			if (Result == null) {
				return response;
			}
			response.setResult(Json.toJson(Result).toString());
			response.setSuccess(true);
			return response;
		} catch (Exception e) {
			log.error(e.getMessage());
			return response;
		}
	}


	public Response deleteOrganization(Organization organization) {
		Response response = new Response();
		response.setSuccess(false);
		//判断是否有下级
		StringBuffer checkChildSbf = new StringBuffer(" select * from sddcgisplatform.organization WHERE parent_Id ='"+organization.getId()+"'");
		String result = userOrganizationDao.queryOrganization(checkChildSbf.toString());
		JSONArray resultJsonArr = new JSONArray(result);
		if(resultJsonArr.length()>0){
			return response;//TODO
		}else{
			try {
				Boolean Result = userOrganizationDao.deleteOrganization(organization);
				if (!Result ) {
					return response;
				}
				response.setSuccess(true);
				response.setResult(Json.toJson(Result).toString());
				return response;
			} catch (Exception e) {
				log.error(e.getMessage());
				return response;
			}
		}
	}


	public Response updateOrganization(Organization organization) {
		Response response = new Response();
		response.setSuccess(false);
		try {
			boolean Result = userOrganizationDao.updateOrganization(organization);
			if (!Result) {
				return response;
			}
			response.setSuccess(true);
			response.setResult(Json.toJson(Result).toString());
			return response;
		} catch (Exception e) {
			log.error(e.getMessage());
			return response;
		}
	 
	}
	
	
	 
}
